<template>
  <div class="agent-management-container">
    <div class="page-header">
      <h1>智能体应用管理中心</h1>
      <div>
        <el-button icon="el-icon-collection" @click="goToKnowledgeBase">我的知识库</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="createAgent">创建智能体应用</el-button>
      </div>
    </div>

    <el-empty v-if="!loading && agentList.length === 0" description="暂无智能体应用">
      <el-button type="primary" size="small" @click="createAgent">立即创建</el-button>
    </el-empty>

    <el-skeleton v-if="loading && agentList.length === 0" :rows="6" animated></el-skeleton>

    <div v-if="agentList.length > 0" class="agent-cards-container" v-loading="loading">
      <el-card v-for="agent in agentList" :key="agent.id" class="agent-card">
        <div slot="header" class="clearfix">
          <span>{{ agent.name }}</span>
          <el-switch
            v-model="agent.isStart"
            :disabled="agent.isStart"
            :loading="agent.statusLoading"
            active-color="#13ce66"
            inactive-color="#ff4949"
            style="float: right;"
            @change="handleStatusChange(agent, $event)"
          ></el-switch>
        </div>
        <div class="card-body">
          <div class="token-info">
            <span>已消耗 Token</span>
            <el-progress :percentage="formatTokenUsage(agent.tokenUsage)" :color="customColorMethod">
              <span>{{ agent.tokenUsage }}</span>
            </el-progress>
          </div>
          <div class="card-actions">
            <el-button type="text" @click="editAgent(agent)">配置</el-button>
            <el-button type="text" class="delete-btn" @click="deleteAgent(agent)">删除</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <div v-if="agentList.length > 0" class="pagination-wrapper">
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="pagination.total"
        :current-page.sync="pagination.pageNum"
        :page-size="pagination.pageSize"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script>
import { getAiAppList, deleteAiApp, startAiApp } from '@/api/api';

export default {
  name: 'aigc',
  data() {
    return {
      loading: false,
      agentList: [],
      pagination: {
        pageNum: 1,
        pageSize: 12,
        total: 0,
      }
    };
  },
  created() {
    this.fetchAgentList();
  },
  methods: {
    goToKnowledgeBase() {
      this.$router.push({ name: 'KnowledgeBase' });
    },
    createAgent() {
      this.$router.push({ name: 'AIGCConfig', params: { id: 'new' } });
    },
    editAgent(agent) {
      this.$router.push({ name: 'AIGCConfig', params: { id: agent.id } });
    },
    deleteAgent(agent) {
      this.$confirm(`确定要删除智能体 "${agent.name}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.handleDeleteAgent(agent.id);
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    async fetchAgentList() {
      this.loading = true;
      try {
        const response = await getAiAppList({
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize,
        });
        if (response.data && response.data.message === '成功') {
          const pageInfo = response.data.data || {};
          const list = pageInfo.list || [];
          this.pagination.total = pageInfo.total || 0;
          this.pagination.pageNum = pageInfo.pageNum || this.pagination.pageNum;
          this.pagination.pageSize = pageInfo.pageSize || this.pagination.pageSize;
          this.agentList = list.map(item => ({
            id: item.id,
            name: item.appName,
            isStart: item.isStart === 1,
            tokenUsage: item.consumptionToken || 0,
            statusLoading: false,
          }));
          if (this.agentList.length === 0 && this.pagination.total > 0 && this.pagination.pageNum > 1) {
            this.pagination.pageNum = Math.max(1, this.pagination.pageNum - 1);
            await this.fetchAgentList();
            return;
          }
        } else {
          this.agentList = [];
          this.$message.error(response.data?.message || '获取智能体列表失败');
        }
      } catch (error) {
        console.error('获取智能体列表失败', error);
        this.$message.error('获取智能体列表失败');
      } finally {
        this.loading = false;
      }
    },
    handlePageChange(page) {
      this.pagination.pageNum = page;
      this.fetchAgentList();
    },
    async handleStatusChange(agent, value) {
      if (!value) {
        agent.isStart = false;
        return;
      }
      agent.statusLoading = true;
      try {
        const response = await startAiApp(agent.id);
        if (response.data && response.data.message === '成功') {
          agent.isStart = true;
          this.$message.success('启用成功');
        } else {
          agent.isStart = false;
          this.$message.error(response.data?.message || '启用失败');
        }
      } catch (error) {
        console.error('启用智能体失败', error);
        agent.isStart = false;
        this.$message.error('启用失败');
      } finally {
        agent.statusLoading = false;
      }
    },
    async handleDeleteAgent(agentId) {
      try {
        const response = await deleteAiApp(agentId);
        if (response.data && response.data.message === '成功') {
          this.$message.success('删除成功');
          await this.fetchAgentList();
        } else {
          this.$message.error(response.data?.message || '删除失败');
        }
      } catch (error) {
        console.error('删除智能体失败', error);
        this.$message.error('删除失败');
      }
    },
    formatTokenUsage(value) {
      const num = Number(value) || 0;
      return Math.max(0, Math.min(num, 100));
    },
    customColorMethod(percentage) {
      if (percentage < 20) {
        return '#f56c6c';
      } else if (percentage < 50) {
        return '#e6a23c';
      } else {
        return '#67c23a';
      }
    }
  },
};
</script>

<style scoped>
.agent-management-container {
  padding: 24px;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #dcdfe6;
}
.page-header h1 {
    font-size: 24px;
    color: #303133;
}

.agent-cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.agent-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.agent-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px 0 rgba(0,0,0,.1);
}

.card-body .token-info {
  margin-bottom: 20px;
}

.card-actions {
  text-align: right;
  border-top: 1px solid #EBEEF5;
  padding-top: 10px;
  margin-top: 10px;
}

.card-actions .el-button {
  padding: 0;
  min-height: auto;
}

.card-actions .delete-btn {
  color: #f56c6c;
  margin-left: 10px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
.el-progress-bar__inner{
    border-radius: 100px;
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>
